from config import globalConf, missionConf
from shareClass import ShareClass

from deepGrabber import DeepGrabber
from repeatGrabber import RepeatGrabber
def grabberMap(missionType, *args, **kwargs):
    print("Creating grabber", missionType)
    '''
        grabberMap 函数根据 missionType 返回一个 Grabber 的实例
        *args 中需要的参数：
        sdsId: subDataStoreId，也即 missionId
        path: 任务的目录
    '''
    if missionType == 1:
        return DeepGrabber(*args, **kwargs)
    if missionType == 2:
        return RepeatGrabber(*args, **kwargs)
    return None

class MissionPanel():

    _grabberPool = {} # key: missionId
                      # value: class
    
    def __init__(self):
        self._mission = missionConf

    def reloadStore(self):
        self._mission.reload()
        print("Store Reloaded!")

    def _loadMission(self, missionId):
        if missionId not in self._grabberPool:
            print("missionId =", missionId, "Loaded.")
            conf = self._mission["mission"][missionId]["config"]
            self._grabberPool[missionId] = grabberMap(
                missionType = conf["missionType"],
                sdsId = int(missionId)
            )
            
    def _unloadMission(self, missionId):
        if missionId in self._grabberPool:
            print("missionId =", missionId, "Unloaded.")
            self._grabberPool.pop(missionId)

    def _getGrabberById(self, missionId):
        return self._grabberPool[missionId]

    def startMission(self, missionId):
        print("Trying to start mission", missionId)
        if isinstance(missionId, int):
            missionId = str(missionId)
        self._loadMission(missionId)
        print("Alive")
        self._getGrabberById(missionId).start()
        print("AfterAlive")
        print("mission", missionId, "started.")

    def stopMission(self, missionId):
        if isinstance(missionId, int):
            missionId = str(missionId)
        self._getGrabberById(missionId).stop()
        print("mission", missionId, "stopped?")
        self._unloadMission(missionId)
        print("mission", missionId, "stopped.")

    def missionStatus(self, missionId):
        print("missionStatus-service Entered.")
        if isinstance(missionId, int):
            missionId = str(missionId)
        if missionId in self._grabberPool:
            grb = self._getGrabberById(missionId)
            return {
                "thread": grb.runningThreadCount() # 这里只获取运行中的信息
            }
        else:
            return {} # 防止 backend 报错

panel = MissionPanel()
sharer = ShareClass()
sharer.share("Panel", panel)

while True:
    pass # start message loop